<template>
  <van-button class="follow-btn"
    round
    size="small"
    @click="onFollow"
    v-if="isFollowed"
    :loading="followLoading">已关注</van-button>
  <van-button class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    v-else
    :loading="followLoading">关注</van-button>
</template>

<script>
import { addFollow, cancelFollow } from '@/api/user'

export default {
  name: 'FollowUser',
  model: {
    prop: 'isFollowed', // 默认是value
    event: 'update-if_followed' // 默认是input
  },
  props: {
    // isFollowed: {
    //   type: Boolean,
    //   required: true
    // },
    // value: {
    //   type: Boolean,
    //   required: true
    // },
    isFollowed: {
      type: Boolean,
      required: true
    },

    autherId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      followLoading: false
    }
  },

  methods: {
    // 点击关注和取消关注的请求
    async onFollow () {
      // 按钮添加 loading 的两个作用：
      //   - 交互反馈
      //   - 防止网络慢用户多次点击按钮导致重复触发点击事件
      // 开启按钮的 loading 状态
      this.followLoading = true
      // console.log(this.article)
      try {
        if (this.isFollowed) {
          // 已关注，发起取消关注请求
          await cancelFollow(this.autherId)
        } else {
          // 未关注，发起关注请求
          await addFollow(this.autherId)
        }

        // 更新视图状态
        // this.is_followed = !this.is_followed
        // this.$emit('update-if_followed', !this.is_followed)
        // this.$emit('input', !this.value)
        this.$emit('update-if_followed', !this.isFollowed)
        // 关闭按钮的 loading 状态
        this.followLoading = false
      } catch (err) {
        // console.log(err)
        let message = '操作失败，请重试！'
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
        // this.$toast('操作失败，请重试')
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
